<template>
    <div class="picking zy-content ">
        <!--查询条件-->

      <div class="searchBox search-box-layout">
        <Row :gutter="24">
          <Col span="4">
            <div>
              <p class="label">{{$t('equipCheck.Result')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.inventoryResult" filterable clearable
                        :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item, index) of statusList" :value="item.value" :label="item.label" :key="index" >
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('equipCheck.Time')}}</p>
              <div class="ipt">
                <Date-picker v-model="searchParams.date" format="yyyy/MM/dd" type="daterange"
                             placement="bottom-end"
                             :placeholder="`${$t('common.selectInfo')}`" style="width: 100%"></Date-picker>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('equipCheck.ListByEntity')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.companyId" filterable @on-change="companySelectChange"
                        clearable
                        :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item, index) of companyList" :value="item.id" :label="item.name" :key="index">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('equipCheck.AccountWarehouse')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.warehouseIdInBook" filterable clearable
                        :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item, index) of warehouseFactoryList" :value="item.id" :label="item.backupName" :key="index">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('equipCheck.CheckByEntity')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.inventoryCompanyId" filterable
                        @on-change="inventoryCompanySelectChange" clearable
                        :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item, index) of companyList" :value="item.id" :label="item.name" :key="index"></Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('equipCheck.CheckByStorehouse')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.warehouseId" filterable clearable
                        :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item, index) of factoryList" :value="item.id" :label="item.backupName" :key="index">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.SpareNumber')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.backupNo" filterable clearable :loading="searchLoading">
                  <Option v-for="(item,index) in numberList" :value="item" :label="item" :key="index"></Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('equipCheck.CheckedBy')}}</p>
              <div class="ipt">
                <Select clearable v-model="searchParams.inventoryBy" filterable>
                  <Option v-for="(item, index) in inventoryByList" :value="item.id" :label="item.realname" :key="index">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label hide-label">--</p>
              <div class="ipt">
                <Button class="search-btn" type="primary"
                        v-has="'inventoryBackupSearch'"
                        @click="changeNum()">
                  {{ $t('common.Query') }}
                </Button>
                <Button v-has="'inventoryBackupSearch'"
                    class="reset-btn"
                    @click="reset()"
                >{{ $t('common.reset') }}
                </Button>
              </div>
            </div>
          </Col>
        </Row>
      </div>

      <div class="list-layout mt16">
        <div class="btns clear">

          <span class="title">{{ $t('common.listInformation') }}</span>
          <Button  v-has="'inventoryBackupExport'"  @click="handleOutRecords">{{ $t('equipCheck.ExportCountingRecords') }}</Button>
          <Button  @click="helpVisible = true">{{ $t('common.help') }}</Button>
<!--            <Button @click="getTableColumns(columns)">-->
<!--                {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}-->
<!--            </Button>-->
        </div>
        <!--表格-->
        <div class="tableContent">
          <Table  class="resizable-table" border @on-column-width-resize="onColumnWidthResize" ellipsis ref="selection" :columns="columns" :data="dataSource"
                 @on-selection-change="handleSelectionChange">
          </Table>
        </div>
        <!--分页-->
        <div class="pageWrap mt16">
          <pageLeftTitle :total="total" :selected="ids.length"/>
          <Page :total="total" :page-size="pageSize" :page-size-opts="pageSizeOption" :current="pageNum"
                @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total/>
        </div>
      </div>
        <Modal :mask-closable="false" v-model="helpVisible" title="帮助" class="modal-content-layout">
            <p class="help">对比结果：</p>
            <p class="help">一致：盘点记录的位置与备件台账位置一致。</p>
            <p class="help">不一致：盘点记录的位置与备件台账位置不一致。</p>
            <p class="help">新增：盘点记录存在该备件，但备件台账不存在该备件（任何区域都不存在）。</p>
            <p class="help">缺失：盘点记录不存在该备件，但是备件台账存在该备件。</p>
            <div slot="footer"></div>
        </Modal>
    </div>
</template>

<script>

import fileDownload from "js-file-download";
import {findOrgByLevel, getUsers, deviceNoAndAssetsNo} from "@/api";
import moment from "moment";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
    name: "sparePartsCheck",
    mixins:[toggleTableOperation],
    components: {},
    data() {
        return {
            helpVisible: false,
            ids: '',
            pageNum: 1,
            pageSize: 10,
            total: 0,
            searchParams: {},
            statusList: [
                {label: "全部", value: ''},
                {label: "不一致", value: 0},
                {label: "一致", value: 1},
                {label: "缺失", value: 2},
                {label: "新增", value: 3},
            ],
            columns: [
              {
                //title: '盘点时间',
                title: `${this.$t('批次号')}`,
                key: 'inventoryNo',
                align: 'center',
                minWidth: 180
              },
                {
                    //title: '盘点时间',
                    title: `${this.$t('equipCheck.Time')}`,
                    key: 'inventoryDate',
                    align: 'center',
                    minWidth: 180,
                    resizable: true
                },
                {
                    // title: `${this.$t('spareParts.company')}`,
                    title: `${this.$t('spareParts.company')}`,
                    key: 'companyName',
                    align: 'center',
                    minWidth: 150,
                    resizable: true
                }, {
                    //title: '台账仓库',
                    title: `${this.$t('equipCheck.AccountWarehouse')}`,
                    key: 'warehouseName',
                    align: 'center',
                    minWidth: 160,
                    resizable: true
                },
                {
                    //title: '台账货架',
                    title: `${this.$t('equipCheck.TaiwanAccountShelf')}`,
                    key: 'shelfName',
                    align: 'center',
                    minWidth: 150,
                    resizable: true
                },
                {
                    // title: '台账库位',
                    title: `${this.$t('equipCheck.Ledger')}`,
                    key: 'locationName',
                    align: 'center',
                    minWidth: 140,
                    resizable: true
                },
                {
                    //title: '盘点仓库',
                    title: `${this.$t('equipCheck.CheckByStorehouse')}`,
                    key: 'inventoryWarehouseName',
                    align: 'center',
                    minWidth: 200,
                    resizable: true
                },
                {
                    //title: `${this.$t('spareParts.PartNo')}`,
                    title: `${this.$t('common.PartNo')}`,
                    key: 'materielNo',
                    align: 'center',
                    minWidth: 120,
                    resizable: true
                },
                {
                    // title: `${this.$t('common.SpareNumber')}`,
                    title: `${this.$t('common.SpareNumber')}`,
                    key: 'backupNo',
                    align: 'center',
                    minWidth: 160,
                    resizable: true
                },
                {
                    //  title: `${this.$t('common.GoodsName')}`,
                    title: `${this.$t('common.GoodsName')}`,
                    key: 'goodsName',
                    align: 'center',
                    minWidth: 120,
                    resizable: true
                },
                {
                    // title: `${this.$t('spareParts.Specification')}`,
                    title: `${this.$t('common.Specification')}`,
                    key: 'specification',
                    align: 'center',
                    minWidth: 120,
                    resizable: true
                },
                {
                    // title: '品牌',
                    title: `${this.$t('spareParts.Brand')}`,
                    key: 'brand',
                    align: 'center',
                    minWidth: 200,
                    resizable: true
                },
                {
                    // title: '备件分类',
                    title: `${this.$t('common.SpareClassification')}`,
                    key: 'sparePartsStr',
                    align: 'center',
                    minWidth: 200,
                    resizable: true
                },
                {
                    //  title: '物品分类',
                    title: `${this.$t('common.Classification')}`,
                    key: 'goodsTypeStr',
                    align: 'center',
                    minWidth: 120,
                    resizable: true
                },
                {
                    // title: '资产类型',
                    title: `${this.$t('spareParts.AssetType')}`,
                    key: 'assetTypeStr',
                    align: 'center',
                    minWidth: 200,
                    resizable: true
                },
                {
                    // title: '盘点人',
                    title: `${this.$t('equipCheck.CheckedBy')}`,
                    key: 'inventoryByStr',
                    align: 'center',
                    minWidth: 120,
                    resizable: true
                },
                {
                    // title: '对比结果',
                    title: `${this.$t('equipCheck.Result')}`,
                    key: 'inventoryResultStr',
                    align: 'center',
                    minWidth: 120,
                    resizable: true
                },
              {
                title: `${this.$t('备注')}`,
                key: 'comment',
                align: 'center',
                minWidth: 120,
                  resizable: true
              }
            ],
            dataSource: [],
            pageSizeOption: [10, 20, 30, 40],
            dateTimeRange: [],
            orgList: [],
            factoryLists: [],
            companyList: [],
            warehouseFactoryList: [],
            factoryList: [],
            inventoryByList: [],
            noList: [],
            numberList: [],
            searchLoading: false,
        }
    },
    created() {
        this.getColumnWidth(this.columns)

        this.getCompanyList()
        this.getUsersList()
        this.getNoList()
        this.changeNum()
        this.handleRemote()
    },
    mounted() {
        // let itemList = JSON.parse(window.localStorage.getItem('USER_URI'))

    },
    methods: {
        handleOutRecords() {
            let params = {};
            for (let key in this.searchParams) {
                if (key === 'orgId' && this.searchParams['orgId']) {
                    const arr = this.searchParams[key]
                    const {length, last = length - 1} = arr
                    this.$set(params, key, arr[last])
                } else {
                    if (this.searchParams[key]) {
                        this.$set(params, key, this.searchParams[key])
                    }
                }
            }
            const filName = '备件盘点'
            this.axios({
                method: 'post',
                url: '/dms/inventory/backup/export',
                responseType: 'blob',
                data: {
                    ...params
                }
            }).then(res => {
                fileDownload(res, filName + '.xlsx')
            })
        },
        //批量操作
        handleSelectionChange(selectionData) {
            console.log(selectionData)
            let arr = []
            selectionData.forEach(item => {
                arr.push(item.id)
            })
            this.ids = arr
        },
      reset(){
          this.searchParams = {};
          this.searchParams.inventoryResult = null;
          this.searchParams.date = [];
          this.changeNum();
      },
        //分页
        changeNum() {
            this.pageNum = 1;
            this.searchList();
        },
        changePageSize(pageSize) {
            this.pageSize = pageSize;
            this.searchList();
        },
        changePageNum(val) {
            this.pageNum = val;
            this.searchList();
        },
        searchList() {//查询列表
            const {date} = this.searchParams
            let params = {
                pageNo: this.pageNum,
                pageSize: this.pageSize,
                // inventoryResult:this.inventoryResult,
            };
            for (let key in this.searchParams) {
                this.$set(params, key, this.searchParams[key])
            }
            if (Array.isArray(date) && date.length > 1) {
                params['inventoryDateStar'] = moment(date[0]).format('YYYY-MM-DD 00:00:00')
                params['inventoryDateEnd'] = date[1] ? moment(date[1]).format('YYYY-MM-DD 23:59:59') : ""
                delete params.date
                if (!date[0]) {
                    delete params['inventoryDateStar']
                }
                if (!date[1]) {
                    delete params['inventoryDateEnd']
                }
            } else {
                delete params['inventoryDateStar']
                delete params['inventoryDateEnd']
            }
            //params.inventoryDateStar =date? moment(date[0]).format('YYYY-MM-DD'):""
            // params.inventoryDateEnd =date? moment(date[1]).format('YYYY-MM-DD'):""

            // for (let key in this.searchParams) {
            //   this.$set(params, key, this.searchParams[key])
            // }


            this.axios({
                method: 'post',
                url: '/dms/inventory/backup/list',
                data: params
            }).then(res => {
                if (res.code === 200) {
                    this.dataSource = res.data.list.map(item => {
                        const obj = this.statusList.find(m => m.value === item.inventoryResult)
                        if (obj) {
                            item.statusName = obj.label
                        }
                        return item;
                    })
                    this.total = res.data.total
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        //获取备件编号
        handleRemote() {
            this.searchLoading = true;
            this.axios({
                method: 'get',
                url: '/dms/standingBook/getBackupNos',
                params: {
                    backupNo: "",
                }
            }).then(res => {
                
                if (res.code === 200) {
                    this.numberList = res.data
                    // .map(item => {
                    //   return {
                    //     ...item,
                    //   codeName: item.maCode + '-' + item.maName
                    //   }
                    // })
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}))
                }
            }).finally(() => {
                this.searchLoading = false
            })
        },
        //获取公司
        getCompanyList() {
            this.axios({
                method: 'get',
                url: '/basic/company/getCompanyListByUser',
            }).then(res => {
                if (res.code === 200) {
                    this.companyList = res.data
                } else {
                    this.companyList = []
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            }).finally(() => {
                this.loading = false
            })
        },
        getWarehouseFactoryList(code, listKey) {
            this.axios({
                method: 'post',
                url: '/dms/dmsBackupConfig/queryBackupsByCompany',
                data: {companyId: this.searchParams.companyId}
            }).then(res => {
                if (res.code === 200) {
                    this[listKey] = res.data
                } else {
                    this[listKey] = []
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            }).finally(() => {
                this.loading = false
            })
        },
        getFactoryList() {
            this.axios({
                url: '/dms/dmsBackupConfig/queryBackupsByCompany',
                method: 'post',

                data: {companyId: this.searchParams.inventoryCompanyId}
            }).then(res => {
                if (res.code === 200) {
                    this.factoryList = res.data
                } else {
                    this.factoryList = []
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            }).finally(() => {
                this.loading = false
            })
        },
        inventoryCompanySelectChange() {

            if (this.searchParams.inventoryCompanyId) {
                this.getFactoryList();
            } else {
                this.factoryList = []
                this.searchParams.warehouseId = ''

            }
        },
        companySelectChange() {
            if (this.searchParams.companyId) {
                this.getWarehouseFactoryList(this.searchParams.companyId, 'warehouseFactoryList');
            } else {
                this.warehouseFactoryList = []
                this.searchParams.warehouseIdInBook = ''
            }
        },
        // companySelectChanges() {
        //   if (this.searchParams.inventoryCompanyCode)
        //     this.getWarehouseFactoryList(this.searchParams.inventoryCompanyCode, 'factoryLists');
        //   else {
        //     this.factoryLists = []
        //     this.searchParams.inventoryFactoryCode = ''
        //   }
        // },
        getUsersList() {
            getUsers({}).then(res => {
                if (res.code === 200) {
                    this.inventoryByList = res.data
                } else {
                    this.inventoryByList = []
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        getNoList() {
            deviceNoAndAssetsNo({deviceNo: "", assetsNo: ""}).then(res => {
                if (res.code === 200) {
                    this.noList = res.data
                } else {
                    this.noList = []
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
    }
}
</script>

<style scoped lang="scss">
.picking {

    .formList {
        padding: 30px;

        .btn {
            margin-top: 20px;
            text-align: center;
            width: 100%;
            height: 40px;
        }

        .inputBorder {
            border: 1px solid #dcdee2;
            border-radius: 4px;

        }
    }


}

.ivu-input-number {
    width: -webkit-fill-available;
}

.help {
    font-family: 'Arial Normal', 'Arial', sans-serif;
    font-weight: 400;
    font-style: normal;
    font-size: 14px;
    line-height: 28px;
    //white-space: nowrap;
}
</style>

<style lang="scss">
</style>
